package com.lhd.qd.common.util;

import com.lhd.qd.common.exception.BusinessException;
import com.lhd.qd.config.QdProperties;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;

@Component
public class TokenUtils {

    private static final String CLAIM_KEY_USER_ID = "uid";

    private static QdProperties qdProperties;
    @Autowired
    public void setQdProperties(QdProperties qdProperties) {
        TokenUtils.qdProperties = qdProperties;
    }

    public static String generate(Long id, Duration duration) {

        if (id == null) {
            throw new BusinessException("生成token参数不正确");
        }

        JwtBuilder jwtBuilder = Jwts.builder()
                .claim(CLAIM_KEY_USER_ID, id)
                .signWith(Keys.hmacShaKeyFor(
                        qdProperties.getTokenSecretKey().getBytes()),
                        SignatureAlgorithm.HS256);

        if (duration != null && duration.getSeconds() > 0) {
            Date expireDate = DateUtils.localDateTime2Date(LocalDateTime.now().plusSeconds(duration.getSeconds()));
            jwtBuilder.setExpiration(expireDate);
        }

        return jwtBuilder.compact();
    }

    public static Long parse(String token) {

        if (StringUtils.isEmpty(token)) {
            throw new BusinessException("解析token参数不正确");
        }

        Object idObj = Jwts.parserBuilder()
                .setSigningKey(qdProperties.getTokenSecretKey().getBytes())
                .build()
                .parseClaimsJws(token)
                .getBody().get(CLAIM_KEY_USER_ID);

        if (idObj != null) {
            return Long.parseLong(idObj.toString());
        }
        return null;
    }

    public static void verify(String token) {

        if (StringUtils.isEmpty(token)) {
            throw new BusinessException("验证token参数不正确");
        }

        Jwts.parserBuilder()
                .setSigningKey(qdProperties.getTokenSecretKey().getBytes())
                .build()
                .parseClaimsJws(token);

    }
}
